﻿using System;
using System.Collections.Generic;

namespace BF
{
    public static class EventManager
    {
        //注意：ushort取值范围为[0, 65535]

        private static Dictionary<ushort, Delegate> _eventListeners = new Dictionary<ushort, Delegate>();

        public static void AddEvent<T>(ushort key, Action<T> listener)
        {
            if (_eventListeners.TryGetValue(key, out Delegate old))
            {
                _eventListeners[key] = Delegate.Combine(old, listener);
            }
            else
            {
                _eventListeners[key] = listener;
            }
        }

        public static void AddEvent(ushort key, Action listener)
        {
            if (_eventListeners.TryGetValue(key, out Delegate old))
            {
                _eventListeners[key] = Delegate.Combine(old, listener);
            }
            else
            {
                _eventListeners[key] = listener;
            }
        }

        public static void InvokeEvent<T>(ushort key, T value)
        {
            if (!_eventListeners.TryGetValue(key, out Delegate @delegate))
            {
                return;
            }

            if (@delegate is Action<T> action)
            {
                action.Invoke(value);
            }
        }

        public static void InvokeEvent(ushort key)
        {
            if (!_eventListeners.TryGetValue(key, out Delegate @delegate))
            {
                return;
            }

            if (@delegate is Action action)
            {
                action.Invoke();
            }
        }

        public static void RemoveEvent<T>(ushort key, Action<T> listener)
        {
            if (!_eventListeners.TryGetValue(key, out Delegate source)) return;

            _eventListeners[key] = Delegate.Remove(source, listener);
        }

        public static void RemoveEvent(ushort key, Action listener)
        {
            if (!_eventListeners.TryGetValue(key, out Delegate source)) return;

            _eventListeners[key] = Delegate.Remove(source, listener);
        }

        public static void RemoveEvent(ushort key)
        {
            if (!_eventListeners.TryGetValue(key, out Delegate source)) return;

            _eventListeners.Remove(key);
        }

        private static void RemoveAllEvent()
        {
            _eventListeners.Clear();
        }
    }
}